package com.sjk.interceptor;

import com.sjk.pojo.LimitToAuthority;
import com.sjk.utils.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.List;

/**
 * @author lohhhha
 * 2023/5/18
 */


public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();

        if (url.contains("/login")) {
            return true;
        } else {
            if (request.getSession().getAttribute("jwt") != null) {
                List<String> info = JWTUtils.checkToken((String) request.getSession().getAttribute("jwt"));
                if (info != null) {
                    // login => check limit level
                    int limit = Integer.parseInt(info.get(1));
                    if(limit>=0){
                        for(String posUrl: LimitToAuthority.limit0Authority){
                            if(url.contains(posUrl)){
                                return true;
                            }
                        }
                    }
                    if(limit>=1){
                        for(String posUrl: LimitToAuthority.limit1Authority){
                            if(url.contains(posUrl)){
                                return true;
                            }
                        }
                    }
                    if(limit>=2){
                        for(String posUrl: LimitToAuthority.limit2Authority){
                            if(url.contains(posUrl)){
                                return true;
                            }
                        }
                    }
                    response.sendRedirect(request.getContextPath() + "/overAuthority");
                } else{
                    // jwt out of date
                    response.sendRedirect(request.getContextPath() + "/login");
                }
            } else {
                response.sendRedirect(request.getContextPath() + "/login");
            }
        }

        return false;
    }
}
